/****************************************************************************
 * Copyright 2010 Huascar A. Sanchez                                        *
 *                                                                          *
 * Licensed under the Apache License, Version 2.0 (the "License");          *
 * you may not use this file except in compliance with the License.         *
 * You may obtain a copy of the License at                                  *
 *                                                                          *
 *     http://www.apache.org/licenses/LICENSE-2.0                           *
 *                                                                          *
 * Unless required by applicable law or agreed to in writing, software      *
 * distributed under the License is distributed on an "AS IS" BASIS,        *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
 * See the License for the specific language governing permissions and      *
 * limitations under the License.                                           *
 ****************************************************************************/
package com.gotobject.filter.common;

import com.gotobject.filter.spi.Function;

import java.util.Map;

/**
 * inspired by the google collections' built-in functions.
 * @author huascar.sanchez@gmail.com (Huascar A. Sanchez)
 */
public class Functions {
    public Functions() {}

    /**
     * The function does not accept nulls; it will throw a
     * {@link NullPointerException} when applied to {@code null}.
     * @return
     *      a function that calls {@code toString()} on its argument
     */
    public static Function<Object, String> toStringFunction() {
        return new Function<Object, String>(){
            @Override
            public String apply(Object from) throws Exception {
                return from.toString();
            }

            @Override
            public String toString() {
                return "toString";
            }
        };
    }

    public static <E> Function<E, E> identity() {
        return new Function<E, E>(){
            @Override
            public E apply(E from) throws Exception {
                return from;
            }
        };
    }

    public static <K,V> Function<K, V> forMap(final Map<K,V> map) {
        return new Function<K, V>(){
            @Override
            public V apply(K from) throws Exception {
                V result = map.get(from);
                if(result == null || !map.containsKey(from)) {
                    throw new IllegalArgumentException(String.format("Key %s not present", from));
                }

                return result;
            }

            @Override
            public String toString() {
                return "forMap(" + map + ")";
            }
        };
    }


}
